package com.hoshiicloud.user.controller.company;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.common.validate.ValidGroupAdd;
import com.hoshiicloud.common.validate.ValidGroupUpdate;
import com.hoshiicloud.user.controller.BaseController;
import com.hoshiicloud.user.entity.company.Company;
import com.hoshiicloud.user.param.company.CompanyAddParam;
import com.hoshiicloud.user.param.company.CompanyPageParam;
import com.hoshiicloud.user.service.company.ICompanyService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 公司 前端控制器
 * </p>
 *
 * @author WGJ
 * @since 2019-04-22
 */
@Slf4j
@RestController
@RequestMapping("/company/company")
@Api(value = "租户", tags = {"SAAS租户"})
@ApiSort(7)
public class CompanyController extends BaseController {

    private final ICompanyService companyService;

    public CompanyController(ICompanyService companyService) {
        this.companyService = companyService;
    }

    /**
     * 根据id查询租户信息
     *
     * @param id ID
     * @return Response<Company>
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "根据ID查询", notes = "根据ID查询租户信息", consumes = MediaType.ALL_VALUE)
    @ApiImplicitParam(name = "id", value = "租户主键ID", required = true, dataType = "Long", example = "3187243209717710848", paramType = "query")
    @ApiOperationSort(3)
    public Response findCompanyById(@PathVariable("id") Long id) {
        return Response.data(companyService.getById(id));
    }

    /**
     * 根据ID组查询租户信息
     *
     * @param ids ID组
     * @return Response<List < Company>>
     */
    @GetMapping("/getByIds")
    @ApiOperation(value = "根据ID组查询", notes = "根据ID组查询租户信息", consumes = MediaType.ALL_VALUE)
    public Response<List<Company>> getByIds(@RequestParam("ids") List<Long> ids) {
        return Response.data(companyService.getByIds(ids));
    }

    /**
     * 根据名称查询
     *
     * @param name 机构名称
     * @return Response<List < Company>>
     */
    @GetMapping("/find/{name}")
    @ApiOperation(value = "查询", notes = "根据名称查询租户信息", consumes = MediaType.ALL_VALUE)
    public Response findByName(@PathVariable("name") String name) {
        return Response.data(companyService.companyList(name));
    }

    /**
     * 分页查询租户信息（post请求，以对象接收参数）
     *
     * @param param 查询参数实体
     * @return Response<IPage < Company>>
     */
    @PostMapping("/list")
    @ApiOperation(value = "分页查询", notes = "分页查询仓库信息", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<IPage<Company>> list(@RequestBody CompanyPageParam param) {
        try {
            QueryWrapper<Company> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .like((param.getName() != null), Company::getName, param.getName())
                    .eq((param.getCreditCode() != null), Company::getCreditCode, param.getCreditCode())
                    .eq((param.getIdCard() != null), Company::getIdCard, param.getIdCard())
                    .eq((param.getShortName() != null), Company::getShortName, param.getShortName())
                    .eq((param.getTelephone() != null), Company::getTelephone, param.getTelephone())
                    .eq(StringUtils.isNotBlank(param.getPrivateDomain()),Company::getPrivateDomain,param.getPrivateDomain())
                    .eq(StringUtils.isNotBlank(param.getLegalPersonName()), Company::getLegalPersonName, param.getLegalPersonName())
                    .orderByDesc(Company::getId);
            IPage<Company> page = new Page<>(Long.parseLong(param.getPageNumber()), Long.parseLong(param.getPageSize()));
            String key = param.toString() + ",Page{pageNumber=" + param.getPageNumber() + ",pageSize=" + param.getPageSize() + "}";
            return Response.data(companyService.getPage(page, queryWrapper, key));
        } catch (Exception e) {
            log.error("分页查询租户信息异常", e);
            return Response.failed("分页查询租户信息异常");
        }

    }


    /**
     * 新增
     *
     * @param company company
     * @return com.hoshiicloud.common.rpc.Response
     */
    @PostMapping("/save")
    @ApiOperation(value = "新增租户",
            notes = "新增租户信息",
            produces = "application/json",
            consumes = "application/json")
    public Response saveCompany(@RequestBody @Validated(value = ValidGroupAdd.class) Company company) {
        return Response.data(companyService.saveCompany(company));
    }

    /**
     * 修改
     *
     * @param company company
     * @return com.hoshiicloud.common.rpc.Response
     */
    @PutMapping("/update")
    @ApiOperation(value = "修改租户",
            notes = "修改租户信息",
            produces = "application/json",
            consumes = "application/json")
    public Response updateCompanyById(@RequestBody @Validated(value = ValidGroupUpdate.class) Company company) {
        return Response.data(companyService.updateById(company));
    }

    /**
     * 根据ID删除租户信息（逻辑删除）
     *
     * @param id 租户ID
     * @return Response<Boolean>
     */
    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "根据ID逻辑删除", notes = "根据ID逻辑删除租户信息", consumes = MediaType.ALL_VALUE)
    @ApiImplicitParam(name = "id", value = "租户ID", required = true, dataType = "Long", example = "3187243209717710848", paramType = "query")
    public Response<Boolean> delete(@PathVariable("id") Long id) {
        // TODO(由于缺少逻辑删除字段这里暂时是假的)
        return Response.data(companyService.delete(id));
    }

    /**
     * 根据ID删除租户信息（物理删除）
     *
     * @param id 租户ID
     * @return Response<Boolean>
     */
    @DeleteMapping("/realDelete/{id}")
    @ApiOperation(value = "根据ID物理删除", notes = "根据ID物理删除租户信息", consumes = MediaType.ALL_VALUE)
    @ApiImplicitParam(name = "id", value = "租户ID", required = true, dataType = "Long", example = "3187243209717710848", paramType = "query")
    public Response<Boolean> realDelete(@PathVariable("id") Long id) {
        return Response.data(companyService.realDelete(id));
    }


    /**
     * 新增
     *
     * @param param supppiler
     * @return com.hoshiicloud.common.rpc.Response
     */
    @PostMapping("/addCompanyAndDepart")
    @ApiOperation(value = "新增租户和管理员",
            notes = "新增租户和管理员信息",
            produces = "application/json",
            consumes = "application/json")
    public Response addCompanyAndDepart(@RequestBody @Validated(value = ValidGroupAdd.class) CompanyAddParam param) {
        return Response.data(companyService.addCompanyAndDepart(param));
    }

    /**
     * 租户注册
     *
     * @param param supppiler
     * @return com.hoshiicloud.common.rpc.Response
     */
    @PostMapping("/companyRegister")
    @ApiOperation(value = "租户注册",
            notes = "租户注册",
            produces = "application/json",
            consumes = "application/json")
    public Response companyRegister(@RequestBody @Validated(value = ValidGroupAdd.class) CompanyAddParam param) {
        return Response.data(companyService.companyRegister(param));
    }

}
